<?php

namespace App\Http\Controllers\Archive;


use App\Helpers\HTML;
use App\Model\Globals;
use App\Model\WechatArticle;
use App\Models\Archive\Archive;
use App\Models\Tag\Tag;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Tag\TagFinder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use App\Helpers\UploadFile;


class WeChatController extends Controller
{
    //内容列表
    public function index(Request $request)
    {
        $query = Archive::where('archive_type_id',4)->where('is_del',0)->orderBy('id','desc');
        if ($request->has('s')) {
            $s = trim($request->input('s'));
            $query->where(function ($query) use($s) {
                $query->where('title', 'like', "%{$s}%");
                $query->orWhere('id', $s);
            });
        }

        $archives = $query->paginate(20);
        $count =  $query->count();
        return view('weChatSpider.index',compact('count'))
                ->with('archives',$archives->appends($request->only(['s'])))
            ;
    }

    public function spiderStart()
    {
        $global = Globals::first();
        $time = time();
        $sign = md5($global->spider_key.$time.$global->spider_secret);
        $spider_url = "http://www.shenjianshou.cn/restv2/crawler/start?user_key=".$global->spider_key."&timestamp=".$time."&sign=".$sign."&crawler_id=".$global->spider_id;

        $oCurl = curl_init();
        if(stripos($spider_url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $spider_url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        curl_close($oCurl);
        return $sContent;
    }

    public function spiderStop()
    {
        $global = Globals::first();
        $time = time();
        $sign = md5($global->spider_key.$time.$global->spider_secret);
        $spider_url = "http://www.shenjianshou.cn/restv2/crawler/stop?user_key=".$global->spider_key."&timestamp=".$time."&sign=".$sign."&crawler_id=".$global->spider_id;

        $oCurl = curl_init();
        if(stripos($spider_url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $spider_url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        curl_close($oCurl);
        return $sContent;
    }

    public function webhook()
    {
        $global = Globals::first();
        $user_secret = $global->spider_secret;
        if($input = Input::all()){
            $sign2 = $input['sign2'];
            $url = $input['url'];
            $timestamp = $input['timestamp'];
            if (md5($url . $user_secret . $timestamp) === $sign2) {
                $data = $input['data'];
                $data = json_decode($data,true);



                DB::beginTransaction();
                $new['title'] = isset($data['article_title'])?$data['article_title']:'';
                //$new['title'] = $this->change($new['title']);
                $new['cover'] = isset($data['article_thumbnail'])?$data['article_thumbnail']:'';
                $new['abstract'] = isset($data['article_brief'])?$data['article_brief']:'';
                $new['visit_count'] = isset($data['article_view_count'])?$data['article_view_count']:0;
                $new['mode'] = 8;
                $new['archive_type_id'] = 4;
                $new['user_id'] = 0;
                $new['created_at'] = date('Y-m-d H:i:s',isset($data['article_publish_time'])?$data['article_publish_time']:0);
/*                if(Archive::where('title',$new['title'])->first()){
                    return $input['data_key'];
                }*/
                if($archive = Archive::create($new)){

                    //$archive->tags()->attach([94,74,98]);


                    $tags = TagFinder::extractTags(strip_tags($data['article_content']),3);
                    foreach ($tags as $key=>$value){
                        $tag[] = $value->word;
                    }
                    $detail['tag_name'] = implode(',',$tag);

                    $this->updateTags($archive, $tag);



                    $detail['archive_id'] = $archive->id;
                    $detail['author'] = isset($data['article_author'])?$data['article_author']:'';

                    $detail['content'] = isset($data['article_content'])?$data['article_content']:'';
                    //$detail['content'] = $this->change($detail['content']);伪原创处理
                    if(WechatArticle::create($detail)){
                        DB::commit();
                        return $input['data_key'];
                    }else{
                        DB::rollback();
                        return false;
                    }
                }
            } else {
                return false;
            }
        }else{
            return false;
        }
    }
    public function updateTags(Archive $archive, $tags)
    {

            $tags = Tag::wrapToIds($tags, true, true);
            $tags = Tag::convertToPrimaries($tags);
            $archive->tags()->attach($tags->all());
            foreach ($tags as $v){
                Tag::where('id',$v)->update(['status'=>2]);
            }
            return $this;
    }
    public function update(Request $request, Archive $archive)
    {
        set_time_limit(0);
        DB::beginTransaction();
        $user = session('user');


        $input = $request->except('_token');
        $subtitle = isset($input['subtitle'])?$input['subtitle']:'';
        $description = isset($input['description'])?$input['description']:'';
        $cate_id = isset($input['category_id'])?$input['category_id']:0;
        $rules = [
            //'title'=>'required|between:3,30|unique:archives,title',
            'tags'=>'required',
            //'category_id'=>'required',
            'content'=>'required',
        ];
        $message = [
            'tags.required' => '标签不能为空',
            'content.required' => '内容或简介不能为空',
        ];
        if ($request->hasFile('cover')) {
            $cover = UploadFile::save($request->file('cover'));
        }

        //banner
        if ($request->hasFile('banner')) {
            $banner = UploadFile::save($request->file('banner'));
        }

        $validator = Validator::make($input,$rules,$message);
        if($validator->passes()){
            $archive->detachPattern(DB::table('patterns')->where('type', 1)->sum('pattern'));
            $archive->mode = $this->calcMode($request, $archive->mode);
            $input = $request->except('content','tags');
            $input['subtitle'] = $subtitle;
            $input['description'] = $description;
            $input['category_id'] = $cate_id;
            $input['cover'] = isset($cover)?$cover:'';
            $input['banner'] = isset($banner)?$banner:'';
            $archive->fill($input);


            $result = $archive->save();
        }else{
            return response()->json(['error'=>1,'msg'=>$validator->errors()]);
        }
        if($result){
            $detail = $request->only(explode(',', $archive->type->fields));
            $this->updateTag($archive, $request->input('tags'));
            $detail['content'] = $this->genContent($detail['content']);
            //匹配最后一个p
            $detail['content'] = str_replace("<p></p>",'',$detail['content']);
            $detail['content'] = str_replace("<p><br /></p>",'',$detail['content']);
            $detail['content'] = str_replace("<p><br></p>",'',$detail['content']);
            if(!WechatArticle::where('archive_id',$archive->id)->update($detail)){
                DB::rollback();
                return response()->json(['error'=>2,'msg'=>'修改失败！']);
            }
            DB::commit();
        }else{
            DB::rollback();
            return response()->json(['error'=>2,'msg'=>'修改失败！']);
        }

        //管理员编辑直接通过审核
        if($user->content_manage){
            $this->toggle($archive,'success');
        }
        return response()->json(['修改成功！', '继续修改']);
    }
    private function calcMode(Request $request, $mode = 0, $flag = 'on')
    {
        $patterns = \DB::table('patterns')
            ->where('type', 1)->get();

        foreach ($request->all() as $key => $i) {
            if ($i == $flag) {
                $p = $patterns->first(function ($p) use($key) {
                    return $p->name == $key;
                });
                $mode |= $p ? $p->pattern : 0;
            }
        }

        return $mode;
    }
    //过滤掉标签首的空白
    private function genContent($content)
    {
        $content = preg_replace('#(<(?:[a-z]|h[1-6])[^>]*>)(?:&nbsp;|\s)+#is', '$1', $content);
        return HTML::filter($content);
    }
    public function toggle(Archive $archive, $name)
    {
        if ($name == 'success') {
            $archive->tags()->update(['status' => 2]);
        }
        //$archive->togglePattern($name);
        //dd($name);
        if($name=='success'){
            $result = $archive->passReview();
        }else{
            $result = $archive->noPassReview();
        }
        if($result){
            return response()->json(['msg' => '操作成功！']);
        }else{
            return response()->json(['msg' => '操作失败！']);
        }
    }
    public function updateTag(Archive $archive, $tags)
    {
        $olds = $archive->tags()->pluck('tags.id');
        if ( ! $olds->isEmpty()) {
            $archive->tags()->detach($olds->all());
        }
        $tags = preg_replace('#，#', ',', $tags);
        $tags = explode(',', $tags);

        if ( ! empty($tags[0])) {
            $tags = array_slice($tags, 0, 3);
            $tags = Tag::wrapToIds($tags, true, true);
            $tags = Tag::convertToPrimaries($tags);
            $archive->tags()->attach($tags->all());
        }

        return $this;
    }

    public function getTxt($count)
    {
        header('Content-Type: plain/text');
        header( "Content-Disposition:   attachment;   filename=wechat_article.txt ");
        if ($count=='500'){
            $ids = Archive::where('archive_type_id',4)->orderBy('id','desc')->take(500)->get();
        }elseif ($count=='1000'){
            $ids = Archive::where('archive_type_id',4)->orderBy('id','desc')->take(1000)->get();
        }elseif ($count=='2000'){
            $ids = Archive::where('archive_type_id',4)->orderBy('id','desc')->take(2000)->get();
        }else{
            $ids = Archive::where('archive_type_id',4)->get();
        }


        foreach ($ids as $v){
            echo "www.qiyiguo.tv/article/".$v->id.".html"."\r\n";
        }
        exit();
    }

    public function change($content)
    {
        ini_set("soap.wsdl_cache_enabled","0");
        $wsdl = 'http://202.75.216.148:81/naipan/NaipanPort?WSDL';
        $param   = array(
            "arg0" => $content,
            "arg1" => "45665078@qq.com",
            "arg2" => "xACdIUi64zfpOluDD2M2tJAK8CxDozU8oOmKb9Mu1+Q="
        );

        $client = new \SoapClient($wsdl);
        $result = $client->getContent($param,1);

        return $result->return;
    }
}
